﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Security.Cryptography;
using System.Text;
using CardRegisterCollection.DBUtility;
using CardRegisterCollection.Model;

//Please add references
namespace CardRegisterCollection.DAL
{
    /// <summary>
    /// 数据访问类:role_menu
    /// </summary>
    public partial class RoleMenu
    {
        public RoleMenu()
        { }
        #region  BasicMethod

        /// <summary>
        /// 得到最大ID
        /// </summary>
        public int GetMaxId()
        {
            return DbHelperOleDb.GetMaxID("ID", "role_menu");
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from role_menu");
            strSql.Append(" where DeleteFlag = 0 ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(strWhere);
            }

            return DbHelperOleDb.Exists(strSql.ToString());
        }

        /// <summary>
        /// 通过用户id与list<menuid></menuid>清空菜单权限表
        /// </summary>
        /// <param name="RoleId"></param>
        /// <returns></returns>
        public int DeleteMenuItemByRoleId(string RoleId)
        {
            string strSql = string.Empty; 
            strSql = "delete  from role_menu where RoleId = @RoleId  ";
            OleDbParameter[] parameters = {
                    new OleDbParameter("@RoleId",RoleId)
            };
            return DbHelperOleDb.ExecuteSql(strSql, parameters);
        }

        /// <summary>
        /// 通过角色ID获取菜单列表
        /// </summary>
        /// <param name="roleIds"></param>
        /// <returns></returns>
        public List<Model.Menu> GetMenuByRoleId(List<string> roleIds)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from menu ");
            if (!roleIds.Contains("1"))
            {
                strSql.Append("where Id in (Select  MenuId from role_menu   where RoleId in (@RoleIds))");
                string ids = string.Join(",", roleIds);
                OleDbParameter[] parameters = {
                    new OleDbParameter("@RoleIds",ids)
            };

                DataSet ds = DbHelperOleDb.Query(strSql.ToString(), parameters);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    return DataTableToModel(ds.Tables[0]);
                }
            }
            else
            {
                DataSet ds = DbHelperOleDb.Query(strSql.ToString());
                if (ds.Tables[0].Rows.Count > 0)
                {
                    return DataTableToModel(ds.Tables[0]);
                }

            }
            return null;
        }
        /// <summary>
        /// DataTable转换成实体类列表
        /// </summary>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private List<Model.Menu> DataTableToModel(DataTable dt)
        {
            List<Model.Menu> menus = new List<Model.Menu>();
            foreach (DataRow dr in dt.Rows)
            {
                Model.Menu menu = new Model.Menu();
                menu.ID = (int)dr["Id"];
                menu.Type = (int)dr["Type"];
                menu.Sort = (int)dr["Sort"];
                menu.ParentId = dr["ParentId"]?.ToString();
                menu.Name = dr["Name"]?.ToString();
                menu.Title = dr["Title"]?.ToString();
                menu.CreatedBy = dr["CreatedBy"]?.ToString();
                menu.LastUpdatedBy = dr["LastUpdatedBy"]?.ToString();
                menu.DeleteFlag = (bool)dr["DeleteFlag"];
                if (dr["CreatedAt"]?.ToString().Length != 0)
                    menu.CreatedAt = (DateTime?)dr["CreatedAt"];
                if (dr["LastUpdatedAt"]?.ToString().Length != 0)
                    menu.LastUpdatedAt = (DateTime?)dr["LastUpdatedAt"];
                menus.Add(menu);
            }
            return menus;
        }
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public bool Add(Model.RoleMenu model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into role_menu(");
            strSql.Append("ID,RoleId,MenuId,CreatedBy,CreatedAt,DeleteFlag )");
            strSql.Append(" values (");
            strSql.Append("@ID,@RoleId,@MenuId,@CreatedBy,@CreatedAt,@DeleteFlag )");
            OleDbParameter[] parameters = {
                 new OleDbParameter("@ID", OleDbType.VarChar,255),
                    new OleDbParameter("@RoleId", OleDbType.VarChar,255),
                    new OleDbParameter("@MenuId", OleDbType.Integer,4),
                    new OleDbParameter("@CreatedBy", OleDbType.VarChar,255),
                    new OleDbParameter("@CreatedAt", OleDbType.Date),
                    new OleDbParameter("@DeleteFlag", OleDbType.Boolean,1), 
                    };
            parameters[0].Value = model.ID;
            parameters[1].Value = model.RoleId;
            parameters[2].Value = model.MenuId;
            parameters[3].Value = model.CreatedBy;
            parameters[4].Value = model.CreatedAt;
            parameters[5].Value = model.DeleteFlag; 
   

            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Model.RoleMenu model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update role_menu set ");
            strSql.Append("RoleId=@RoleId,");
            strSql.Append("MenuId=@MenuId,");
            strSql.Append("DeleteFlag=@DeleteFlag,");
            strSql.Append("LastUpdatedBy=@LastUpdatedBy,");
            strSql.Append("LastUpdatedAt=@LastUpdatedAt");
            strSql.Append(" where ID=@ID");
            OleDbParameter[] parameters = {
                    new OleDbParameter("@RoleId", OleDbType.VarChar,255),
                    new OleDbParameter("@MenuId", OleDbType.Integer,4),
                    new OleDbParameter("@DeleteFlag", OleDbType.Boolean,1),
                    new OleDbParameter("@LastUpdatedBy", OleDbType.VarChar,255),
                    new OleDbParameter("@LastUpdatedAt", OleDbType.Date),
                    new OleDbParameter("@ID", OleDbType.Integer,4)};
            parameters[0].Value = model.RoleId;
            parameters[1].Value = model.MenuId;
            parameters[2].Value = model.DeleteFlag;
            parameters[3].Value = CurrentLoginInfo.UserInfo.UserName;
            parameters[4].Value = DateTime.Now;
            parameters[5].Value = model.ID;

            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(string ID)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from role_menu ");
            strSql.Append(" where ID=@ID");
            OleDbParameter[] parameters = {
                    new OleDbParameter("@ID", OleDbType.VarChar,255)
            };
            parameters[0].Value = ID;

            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 批量删除数据
        /// </summary>
        public bool DeleteList(string IDlist)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from role_menu ");
            strSql.Append(" where ID in (" + IDlist + ")  ");
            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString());
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.RoleMenu GetModel(int ID)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ID,RoleId,MenuId,CreatedBy,CreatedAt,DeleteFlag,LastUpdatedBy,LastUpdatedAt from role_menu ");
            strSql.Append(" where ID=@ID");
            OleDbParameter[] parameters = {
                    new OleDbParameter("@ID", OleDbType.Integer,4)
            };
            parameters[0].Value = ID;

            Model.RoleMenu model = new Model.RoleMenu();
            DataSet ds = DbHelperOleDb.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.RoleMenu DataRowToModel(DataRow row)
        {
            Model.RoleMenu model = new Model.RoleMenu();
            if (row != null)
            {
                if (row["ID"] != null && row["ID"].ToString() != "")
                {
                    model.ID = row["ID"].ToString();
                }
                if (row["RoleId"] != null && row["RoleId"].ToString() != "")
                {
                    model.RoleId = row["RoleId"].ToString() ;
                }
                if (row["MenuId"] != null && row["MenuId"].ToString() != "")
                {
                    model.MenuId = int.Parse(row["MenuId"].ToString());
                }
                if (row["CreatedBy"] != null)
                {
                    model.CreatedBy = row["CreatedBy"].ToString();
                }
                if (row["CreatedAt"] != null && row["CreatedAt"].ToString() != "")
                {
                    model.CreatedAt = DateTime.Parse(row["CreatedAt"].ToString());
                }
                if (row["DeleteFlag"] != null && row["DeleteFlag"].ToString() != "")
                {
                    if ((row["DeleteFlag"].ToString() == "1") || (row["DeleteFlag"].ToString().ToLower() == "true"))
                    {
                        model.DeleteFlag = true;
                    }
                    else
                    {
                        model.DeleteFlag = false;
                    }
                }
                if (row["LastUpdatedBy"] != null)
                {
                    model.LastUpdatedBy = row["LastUpdatedBy"].ToString();
                }
                if (row["LastUpdatedAt"] != null && row["LastUpdatedAt"].ToString() != "")
                {
                    model.LastUpdatedAt = DateTime.Parse(row["LastUpdatedAt"].ToString());
                }
            }
            return model;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ID,RoleId,MenuId,CreatedBy,CreatedAt,DeleteFlag,LastUpdatedBy,LastUpdatedAt ");
            strSql.Append(" FROM role_menu ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            return DbHelperOleDb.Query(strSql.ToString());
        }

        /// <summary>
        /// 获取记录总数
        /// </summary>
        public int GetRecordCount(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) FROM role_menu ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            object obj = DbHelperSQL.GetSingle(strSql.ToString());
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("SELECT * FROM ( ");
            strSql.Append(" SELECT ROW_NUMBER() OVER (");
            if (!string.IsNullOrEmpty(orderby.Trim()))
            {
                strSql.Append("order by T." + orderby);
            }
            else
            {
                strSql.Append("order by T.ID desc");
            }
            strSql.Append(")AS Row, T.*  from role_menu T ");
            if (!string.IsNullOrEmpty(strWhere.Trim()))
            {
                strSql.Append(" WHERE " + strWhere);
            }
            strSql.Append(" ) TT");
            strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
            return DbHelperOleDb.Query(strSql.ToString());
        }

        /*
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetList(int PageSize,int PageIndex,string strWhere)
		{
			OleDbParameter[] parameters = {
					new OleDbParameter("@tblName", OleDbType.VarChar, 255),
					new OleDbParameter("@fldName", OleDbType.VarChar, 255),
					new OleDbParameter("@PageSize", OleDbType.Integer),
					new OleDbParameter("@PageIndex", OleDbType.Integer),
					new OleDbParameter("@IsReCount", OleDbType.Boolean),
					new OleDbParameter("@OrderType", OleDbType.Boolean),
					new OleDbParameter("@strWhere", OleDbType.VarChar,1000),
					};
			parameters[0].Value = "role_menu";
			parameters[1].Value = "ID";
			parameters[2].Value = PageSize;
			parameters[3].Value = PageIndex;
			parameters[4].Value = 0;
			parameters[5].Value = 0;
			parameters[6].Value = strWhere;	
			return DbHelperOleDb.RunProcedure("UP_GetRecordByPage",parameters,"ds");
		}*/

        #endregion  BasicMethod
        #region  ExtensionMethod

        #endregion  ExtensionMethod
    }
}

